/**
 * @TLVHttpEndpoint.java  COPYRIGHT xiaojian
 * 
 * Created on 2018年11月15日 下午3:56:59
 */
package xj.toolkit.netty.transport.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import xj.toolkit.bean.json.JSONSignal;
import xj.toolkit.bean.json.annotation.JSONMessage;
import xj.toolkit.bean.tlv.annotation.TlvType;
import xj.toolkit.bean.tlv.encode.encoders.BeanTLVEncoder;
import xj.toolkit.netty.util.NettyConstants;
import xj.toolkit.util.ByteUtils;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class TLVHttpEndpoint extends HttpEndpoint {

	private static final Logger logger = LoggerFactory.getLogger(JsonHttpEndpoint.class);

	private int dumpBytes = 256;

	private boolean isDebugEnabled;

	private BeanTLVEncoder tlvEncoder;

	@Override
	public byte[] makeHttpBody(Object requestBean, Object response) {

		byte[] result = ByteUtils.union(tlvEncoder.encode(response,
				tlvEncoder.getEncodeContextFactory().createEncodeContext(response.getClass(), null)));

		if (logger.isDebugEnabled()) {
			logger.debug("sendback bean as Hex \r\n{} ", ByteUtils.bytesAsTLVHexString(result, 8096));
		}

		return result;
	}

	@Override
	protected void beforeSend(HttpRequest httpRequest, FullHttpResponse response, Object responseBean) {
		response.headers().add(HttpHeaders.Names.CONTENT_TYPE, NettyConstants.JSON_TYPE);
		// -- MsgCode
		TlvType tlvType = responseBean.getClass().getAnnotation(TlvType.class);
		if (tlvType != null) {
			response.headers().add(NettyConstants.HEADER_MESSAGE_CODE, tlvType.tag());
		}
	}

	public int getDumpBytes() {
		return dumpBytes;
	}

	public void setDumpBytes(int dumpBytes) {
		this.dumpBytes = dumpBytes;
	}

	public boolean isDebugEnabled() {
		return isDebugEnabled;
	}

	public void setDebugEnabled(boolean isDebugEnabled) {
		this.isDebugEnabled = isDebugEnabled;
	}

	public BeanTLVEncoder getTlvEncoder() {
		return tlvEncoder;
	}

	public void setTlvEncoder(BeanTLVEncoder tlvEncoder) {
		this.tlvEncoder = tlvEncoder;
	}

}